<!--
 * @Description: 订单统计页面 - 提供订单数据的统计分析和可视化展示
 * @Author: lujq
 * @Date: 2024-12-21
 * @LastEditors: lujq
 * @LastEditTime: 2024-12-21 11:15:00
-->
<template>
  <div class="order-statistics">
    <!-- 统计概览 -->
    <div class="overview-section">
      <el-row :gutter="20">
        <el-col :xs="24" :sm="12" :md="6" v-for="item in overviewData" :key="item.title">
          <el-card class="overview-card" shadow="hover">
            <div class="card-content">
              <div class="card-icon" :style="{ backgroundColor: item.color }">
                <el-icon :size="20">
                  <component :is="item.icon" />
                </el-icon>
              </div>
              <div class="card-info">
                <div class="card-title">{{ item.title }}</div>
                <div class="card-value">{{ item.value }}</div>
                <div class="card-trend" :class="item.trend > 0 ? 'positive' : 'negative'">
                  <el-icon size="12">
                    <ArrowUp v-if="item.trend > 0" />
                    <ArrowDown v-else />
                  </el-icon>
                  {{ Math.abs(item.trend) }}%
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 筛选条件 -->
    <div class="filter-section">
      <el-card>
        <el-form :model="filterForm" :inline="true" class="filter-form">
          <el-form-item label="时间范围">
            <el-date-picker
              v-model="filterForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              @change="handleFilter"
            />
          </el-form-item>
          <el-form-item label="订单状态">
            <el-select
              v-model="filterForm.status"
              placeholder="请选择订单状态"
              style="width: 200px"
              clearable
              @change="handleFilter"
              @clear="handleFilter"
            >
              <el-option label="待确认" value="pending" />
              <el-option label="已确认" value="confirmed" />
              <el-option label="生产中" value="producing" />
              <el-option label="已完成" value="completed" />
              <el-option label="已取消" value="cancelled" />
            </el-select>
          </el-form-item>
          <el-form-item label="客户类型">
            <el-select
              v-model="filterForm.customerType"
              placeholder="请选择客户类型"
              style="width: 200px"
              clearable
              @change="handleFilter"
              @clear="handleFilter"
            >
              <el-option label="新客户" value="new" />
              <el-option label="老客户" value="old" />
              <el-option label="VIP客户" value="vip" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleFilter">
              <el-icon><Search /></el-icon>
              查询
            </el-button>
            <el-button @click="handleReset">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
            <el-button type="success" @click="handleExport">
              <el-icon><Download /></el-icon>
              导出
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <!-- 图表统计区域 -->
    <div class="charts-section">
      <el-row :gutter="20">
        <!-- 订单趋势图 -->
        <el-col :xs="24" :lg="12">
          <el-card class="chart-card">
            <template #header>
              <div class="card-header">
                <span class="card-title">订单趋势</span>
                <el-select v-model="trendPeriod" size="small" style="width: 120px">
                  <el-option label="最近7天" value="7d" />
                  <el-option label="最近30天" value="30d" />
                  <el-option label="最近90天" value="90d" />
                </el-select>
              </div>
            </template>
            <div ref="orderTrendChart" class="chart-container"></div>
          </el-card>
        </el-col>

        <!-- 订单状态分布 -->
        <el-col :xs="24" :lg="12">
          <el-card class="chart-card">
            <template #header>
              <span class="card-title">订单状态分布</span>
            </template>
            <div ref="orderStatusChart" class="chart-container"></div>
          </el-card>
        </el-col>
      </el-row>

      <el-row :gutter="20" style="margin-top: 20px">
        <!-- 月度销售额 -->
        <el-col :xs="24" :lg="12">
          <el-card class="chart-card">
            <template #header>
              <span class="card-title">月度销售额</span>
            </template>
            <div ref="monthlySalesChart" class="chart-container"></div>
          </el-card>
        </el-col>

        <!-- 产品销售排行 -->
        <el-col :xs="24" :lg="12">
          <el-card class="chart-card">
            <template #header>
              <span class="card-title">产品销售排行</span>
            </template>
            <div ref="productRankChart" class="chart-container"></div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 客户订单分析 -->
      <el-row style="margin-top: 20px">
        <el-col :span="24">
          <el-card class="chart-card">
            <template #header>
              <span class="card-title">客户订单分析</span>
            </template>
            <div ref="customerOrderChart" class="chart-container" style="height: 400px"></div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 数据表格 -->
    <div class="data-section">
      <el-row :gutter="20">
        <!-- 热销产品 -->
        <el-col :xs="24" :lg="12">
          <el-card class="table-card">
            <template #header>
              <div class="card-header">
                <span class="card-title">热销产品</span>
                <el-button type="text" size="small" @click="viewAllProducts"> 查看全部 </el-button>
              </div>
            </template>
            <el-table :data="hotProducts" stripe>
              <el-table-column prop="name" label="产品名称" />
              <el-table-column prop="sales" label="销量" width="80" align="right" />
              <el-table-column prop="revenue" label="销售额" width="100" align="right">
                <template #default="{ row }"> ¥{{ formatNumber(row.revenue) }} </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-col>

        <!-- 大客户订单 -->
        <el-col :xs="24" :lg="12">
          <el-card class="table-card">
            <template #header>
              <div class="card-header">
                <span class="card-title">大客户订单</span>
                <el-button type="text" size="small" @click="viewAllOrders"> 查看全部 </el-button>
              </div>
            </template>
            <el-table :data="bigOrders" stripe>
              <el-table-column prop="customerName" label="客户名称" />
              <el-table-column prop="orderCount" label="订单数" width="80" align="right" />
              <el-table-column prop="totalAmount" label="总金额" width="100" align="right">
                <template #default="{ row }"> ¥{{ formatNumber(row.totalAmount) }} </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick, watch } from 'vue'
import * as echarts from 'echarts'
import {
  ShoppingCart,
  Money,
  TrendCharts,
  User,
  ArrowUp,
  ArrowDown,
  Search,
  Refresh,
  Download,
} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { formatNumber } from '@/utils'
import router from '@/router'

// 图表实例
const orderTrendChart = ref<HTMLElement>()
const orderStatusChart = ref<HTMLElement>()
const monthlySalesChart = ref<HTMLElement>()
const productRankChart = ref<HTMLElement>()
const customerOrderChart = ref<HTMLElement>()

let orderTrendChartInstance: echarts.ECharts
let orderStatusChartInstance: echarts.ECharts
let monthlySalesChartInstance: echarts.ECharts
let productRankChartInstance: echarts.ECharts
let customerOrderChartInstance: echarts.ECharts

// 筛选表单
const filterForm = reactive({
  dateRange: [] as string[],
  status: '',
  customerType: '',
})

// 数据
const trendPeriod = ref('30d')

// 概览数据
const overviewData = ref([
  {
    title: '总订单数',
    value: '2,456',
    trend: 15.2,
    icon: 'ShoppingCart',
    color: '#409EFF',
  },
  {
    title: '总销售额',
    value: '¥1.2M',
    trend: 8.7,
    icon: 'Money',
    color: '#67C23A',
  },
  {
    title: '平均订单额',
    value: '¥4,890',
    trend: -2.3,
    icon: 'TrendCharts',
    color: '#E6A23C',
  },
  {
    title: '活跃客户',
    value: '892',
    trend: 12.1,
    icon: 'User',
    color: '#F56C6C',
  },
])

// 热销产品数据
const hotProducts = ref([
  { name: '高档真丝面料', sales: 156, revenue: 234000 },
  { name: '纯棉印花布', sales: 134, revenue: 189000 },
  { name: '羊毛呢料', sales: 128, revenue: 256000 },
  { name: '亚麻混纺布', sales: 98, revenue: 147000 },
  { name: '涤纶面料', sales: 87, revenue: 98000 },
])

// 大客户订单数据
const bigOrders = ref([
  { customerName: '上海时装有限公司', orderCount: 45, totalAmount: 567000 },
  { customerName: '北京服饰集团', orderCount: 38, totalAmount: 489000 },
  { customerName: '广州纺织厂', orderCount: 32, totalAmount: 423000 },
  { customerName: '深圳制衣公司', orderCount: 28, totalAmount: 356000 },
  { customerName: '杭州丝绸企业', orderCount: 25, totalAmount: 298000 },
])

/**
 * 处理筛选查询
 */
const handleFilter = () => {
  // 根据筛选条件更新数据
  updateDataByFilter()
  
  // 重新渲染图表
  updateCharts()
  
  ElMessage.success('筛选条件已应用')
  console.log('筛选条件:', filterForm)
}

/**
 * 重置筛选条件
 */
const handleReset = () => {
  filterForm.dateRange = []
  filterForm.status = ''
  filterForm.customerType = ''
  
  // 重置数据到初始状态
  resetToInitialData()
  
  // 重新渲染图表
  updateCharts()
  
  ElMessage.info('筛选条件已重置')
}

/**
 * 导出统计数据
 */
const handleExport = async () => {
  try {
    // 动态导入xlsx库
    const XLSX = await import('xlsx')

    // 创建工作簿
    const workbook = XLSX.utils.book_new()

    // 1. 概览数据工作表
    const overviewExportData = [
      ['指标名称', '数值', '增长率'],
      ...overviewData.value.map((item) => [
        item.title,
        item.value,
        `${item.trend > 0 ? '+' : ''}${item.trend}%`,
      ]),
    ]
    const overviewSheet = XLSX.utils.aoa_to_sheet(overviewExportData)
    XLSX.utils.book_append_sheet(workbook, overviewSheet, '统计概览')

    // 2. 热销产品工作表
    const productData = [
      ['产品名称', '销量', '销售额'],
      ...hotProducts.value.map((product) => [product.name, product.sales, product.revenue]),
    ]
    const productSheet = XLSX.utils.aoa_to_sheet(productData)
    XLSX.utils.book_append_sheet(workbook, productSheet, '热销产品')

    // 3. 大客户订单工作表
    const customerData = [
      ['客户名称', '订单数', '总金额'],
      ...bigOrders.value.map((customer) => [
        customer.customerName,
        customer.orderCount,
        customer.totalAmount,
      ]),
    ]
    const customerSheet = XLSX.utils.aoa_to_sheet(customerData)
    XLSX.utils.book_append_sheet(workbook, customerSheet, '大客户订单')

    // 4. 月度销售数据工作表
    const monthlyData = [
      ['月份', '订单数量', '销售额(万元)'],
      ['1月', 156, 78],
      ['2月', 189, 95],
      ['3月', 234, 117],
      ['4月', 198, 99],
      ['5月', 267, 134],
      ['6月', 298, 149],
      ['7月', 345, 173],
      ['8月', 389, 195],
      ['9月', 423, 212],
      ['10月', 456, 228],
      ['11月', 489, 245],
      ['12月', 523, 262],
    ]
    const monthlySheet = XLSX.utils.aoa_to_sheet(monthlyData)
    XLSX.utils.book_append_sheet(workbook, monthlySheet, '月度销售')

    // 设置列宽
    const setColumnWidths = (sheet: any) => {
      const cols = [
        { wch: 20 }, // 第一列
        { wch: 15 }, // 第二列
        { wch: 15 }, // 第三列
      ]
      sheet['!cols'] = cols
    }

    setColumnWidths(overviewSheet)
    setColumnWidths(productSheet)
    setColumnWidths(customerSheet)
    setColumnWidths(monthlySheet)

    // 生成文件名
    const now = new Date()
    const dateStr = now.toISOString().split('T')[0]
    const fileName = `订单统计报告_${dateStr}.xlsx`

    // 导出文件
    XLSX.writeFile(workbook, fileName)

    ElMessage.success('统计报告导出成功！')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败，请重试')
  }
}

/**
 * 查看全部产品
 */
const viewAllProducts = () => {
  router.push('/product/list')
}

/**
 * 查看全部订单
 */
const viewAllOrders = () => {
  router.push('/order/list')
}

/**
 * 初始化订单趋势图表
 */
const initOrderTrendChart = () => {
  if (!orderTrendChart.value) return

  orderTrendChartInstance = echarts.init(orderTrendChart.value)

  // 根据时间周期生成数据
  const { xAxisData, orderData, salesData } = generateTrendData()
  
  const option = {
    tooltip: {
      trigger: 'axis',
    },
    legend: {
      data: ['订单数量', '销售额'],
    },
    xAxis: {
      type: 'category',
      data: xAxisData,
    },
    yAxis: [
      {
        type: 'value',
        name: '订单数量',
        position: 'left',
      },
      {
        type: 'value',
        name: '销售额(万元)',
        position: 'right',
      },
    ],
    series: [
      {
        name: '订单数量',
        type: 'bar',
        yAxisIndex: 0,
        data: orderData,
        itemStyle: {
          color: '#409EFF',
        },
      },
      {
        name: '销售额',
        type: 'line',
        yAxisIndex: 1,
        data: salesData,
        smooth: true,
        itemStyle: {
          color: '#67C23A',
        },
      },
    ],
  }

  orderTrendChartInstance.setOption(option)
}

/**
 * 初始化订单状态图表
 */
const initOrderStatusChart = () => {
  if (!orderStatusChart.value) return

  orderStatusChartInstance = echarts.init(orderStatusChart.value)

  // 根据筛选条件生成数据
  const statusData = generateStatusData()
  
  const option = {
    tooltip: {
      trigger: 'item',
    },
    legend: {
      orient: 'vertical',
      left: 'left',
    },
    series: [
      {
        name: '订单状态',
        type: 'pie',
        radius: '50%',
        data: statusData,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)',
          },
        },
      },
    ],
  }

  orderStatusChartInstance.setOption(option)
}

/**
 * 初始化月度销售额图表
 */
const initMonthlySalesChart = () => {
  if (!monthlySalesChart.value) return

  monthlySalesChartInstance = echarts.init(monthlySalesChart.value)

  // 根据筛选条件生成数据
  const salesData = generateMonthlySalesData()
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow',
      },
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
    },
    yAxis: {
      type: 'value',
      name: '销售额(万元)',
    },
    series: [
      {
        name: '销售额',
        type: 'bar',
        data: salesData,
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#83bff6' },
            { offset: 0.5, color: '#188df0' },
            { offset: 1, color: '#188df0' },
          ]),
        },
      },
    ],
  }

  monthlySalesChartInstance.setOption(option)
}

/**
 * 初始化产品排行图表
 */
const initProductRankChart = () => {
  if (!productRankChart.value) return

  productRankChartInstance = echarts.init(productRankChart.value)

  // 根据筛选条件生成数据
  const rankData = generateProductRankData()
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow',
      },
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true,
    },
    xAxis: {
      type: 'value',
    },
    yAxis: {
      type: 'category',
      data: ['涤纶面料', '亚麻混纺布', '羊毛呢料', '纯棉印花布', '高档真丝面料'],
    },
    series: [
      {
        name: '销量',
        type: 'bar',
        data: rankData,
        itemStyle: {
          color: '#E6A23C',
        },
      },
    ],
  }

  productRankChartInstance.setOption(option)
}

/**
 * 初始化客户订单分析图表
 */
const initCustomerOrderChart = () => {
  if (!customerOrderChart.value) return

  customerOrderChartInstance = echarts.init(customerOrderChart.value)

  // 根据筛选条件生成数据
  const customerData = generateCustomerOrderData()
  
  const option = {
    tooltip: {
      trigger: 'axis',
    },
    legend: {
      data: ['新客户订单', '老客户订单', 'VIP客户订单'],
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
    },
    yAxis: {
      type: 'value',
    },
    series: [
      {
        name: '新客户订单',
        type: 'line',
        stack: 'Total',
        data: customerData.newCustomer,
        smooth: true,
      },
      {
        name: '老客户订单',
        type: 'line',
        stack: 'Total',
        data: customerData.oldCustomer,
        smooth: true,
      },
      {
        name: 'VIP客户订单',
        type: 'line',
        stack: 'Total',
        data: customerData.vipCustomer,
        smooth: true,
      },
    ],
  }

  customerOrderChartInstance.setOption(option)
}

// 监听趋势周期变化
watch(trendPeriod, () => {
  console.log('更新订单趋势:', trendPeriod.value)
  // 重新渲染订单趋势图表
  nextTick(() => {
    initOrderTrendChart()
  })
})

/**
 * 根据时间周期和筛选条件生成趋势数据
 */
const generateTrendData = () => {
  let xAxisData: string[] = []
  let baseOrderData: number[] = []
  let baseSalesData: number[] = []
  
  // 根据时间周期生成不同的数据
  if (trendPeriod.value === '7d') {
    xAxisData = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
    baseOrderData = [45, 52, 38, 48, 35, 78, 69]
    baseSalesData = [23, 26, 19, 24, 18, 39, 35]
  } else if (trendPeriod.value === '30d') {
    xAxisData = Array.from({ length: 30 }, (_, i) => `${i + 1}日`)
    baseOrderData = Array.from({ length: 30 }, () => Math.floor(Math.random() * 50) + 20)
    baseSalesData = baseOrderData.map(val => Math.floor(val * 0.5) + Math.floor(Math.random() * 10))
  } else { // 90d
    xAxisData = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
    baseOrderData = [156, 189, 234, 198, 267, 298, 345, 389, 423, 456, 489, 523]
    baseSalesData = [78, 95, 117, 99, 134, 149, 173, 195, 212, 228, 245, 262]
  }
  
  // 根据筛选条件调整数据
  const hasFilter = filterForm.status || filterForm.customerType || filterForm.dateRange.length > 0
  if (hasFilter) {
    const filterMultiplier = Math.random() * 0.4 + 0.8 // 0.8-1.2之间的随机数
    const orderData = baseOrderData.map(val => Math.floor(val * filterMultiplier))
    const salesData = baseSalesData.map(val => Math.floor(val * filterMultiplier))
    return { xAxisData, orderData, salesData }
  }
  
  return { xAxisData, orderData: baseOrderData, salesData: baseSalesData }
}

/**
 * 根据筛选条件生成订单状态数据
 */
const generateStatusData = () => {
  const baseData = [
    { value: 456, name: '已完成' },
    { value: 234, name: '生产中' },
    { value: 156, name: '已确认' },
    { value: 89, name: '待确认' },
    { value: 45, name: '已取消' },
  ]
  
  // 根据筛选条件调整数据
  const hasFilter = filterForm.status || filterForm.customerType || filterForm.dateRange.length > 0
  if (hasFilter) {
    const filterMultiplier = Math.random() * 0.4 + 0.8 // 0.8-1.2之间的随机数
    return baseData.map(item => ({
      ...item,
      value: Math.floor(item.value * filterMultiplier)
    }))
  }
  
  return baseData
}

/**
 * 根据筛选条件生成月度销售数据
 */
const generateMonthlySalesData = () => {
  const baseData = [78, 95, 117, 99, 134, 149, 173, 195, 212, 228, 245, 262]
  
  // 根据筛选条件调整数据
  const hasFilter = filterForm.status || filterForm.customerType || filterForm.dateRange.length > 0
  if (hasFilter) {
    const filterMultiplier = Math.random() * 0.4 + 0.8 // 0.8-1.2之间的随机数
    return baseData.map(val => Math.floor(val * filterMultiplier))
  }
  
  return baseData
}

/**
 * 根据筛选条件生成产品排行数据
 */
const generateProductRankData = () => {
  const baseData = [87, 98, 128, 134, 156]
  
  // 根据筛选条件调整数据
  const hasFilter = filterForm.status || filterForm.customerType || filterForm.dateRange.length > 0
  if (hasFilter) {
    const filterMultiplier = Math.random() * 0.4 + 0.8 // 0.8-1.2之间的随机数
    return baseData.map(val => Math.floor(val * filterMultiplier))
  }
  
  return baseData
}

/**
 * 根据筛选条件生成客户订单分析数据
 */
const generateCustomerOrderData = () => {
  const baseNewCustomer = [45, 52, 38, 48, 35, 78, 69, 58, 62, 78, 89, 95]
  const baseOldCustomer = [78, 89, 134, 98, 156, 145, 189, 234, 267, 298, 323, 356]
  const baseVipCustomer = [33, 48, 62, 52, 76, 75, 87, 97, 94, 80, 77, 72]
  
  // 根据筛选条件调整数据
  const hasFilter = filterForm.status || filterForm.customerType || filterForm.dateRange.length > 0
  if (hasFilter) {
    const filterMultiplier = Math.random() * 0.4 + 0.8 // 0.8-1.2之间的随机数
    return {
      newCustomer: baseNewCustomer.map(val => Math.floor(val * filterMultiplier)),
      oldCustomer: baseOldCustomer.map(val => Math.floor(val * filterMultiplier)),
      vipCustomer: baseVipCustomer.map(val => Math.floor(val * filterMultiplier))
    }
  }
  
  return {
    newCustomer: baseNewCustomer,
    oldCustomer: baseOldCustomer,
    vipCustomer: baseVipCustomer
  }
}

/**
 * 根据筛选条件更新数据
 */
const updateDataByFilter = () => {
  // 模拟根据筛选条件更新概览数据
  if (filterForm.status || filterForm.customerType || filterForm.dateRange.length > 0) {
    // 根据筛选条件调整数据
    const filterMultiplier = Math.random() * 0.4 + 0.8 // 0.8-1.2之间的随机数
    
    overviewData.value = [
      {
        title: '总订单数',
        value: Math.floor(2456 * filterMultiplier).toLocaleString(),
        trend: Math.round((Math.random() - 0.5) * 30 * 10) / 10,
        icon: 'ShoppingCart',
        color: '#409EFF',
      },
      {
        title: '总销售额',
        value: `¥${(1.2 * filterMultiplier).toFixed(1)}M`,
        trend: Math.round((Math.random() - 0.5) * 20 * 10) / 10,
        icon: 'Money',
        color: '#67C23A',
      },
      {
        title: '平均订单额',
        value: `¥${Math.floor(4890 * filterMultiplier).toLocaleString()}`,
        trend: Math.round((Math.random() - 0.5) * 15 * 10) / 10,
        icon: 'TrendCharts',
        color: '#E6A23C',
      },
      {
        title: '活跃客户',
        value: Math.floor(892 * filterMultiplier).toLocaleString(),
        trend: Math.round((Math.random() - 0.5) * 25 * 10) / 10,
        icon: 'User',
        color: '#F56C6C',
      },
    ]
    
    // 更新热销产品数据
    hotProducts.value = hotProducts.value.map(product => ({
      ...product,
      sales: Math.floor(product.sales * filterMultiplier),
      revenue: Math.floor(product.revenue * filterMultiplier)
    }))
    
    // 更新大客户订单数据
    bigOrders.value = bigOrders.value.map(order => ({
      ...order,
      orderCount: Math.floor(order.orderCount * filterMultiplier),
      totalAmount: Math.floor(order.totalAmount * filterMultiplier)
    }))
  }
}

/**
 * 更新所有图表
 */
const updateCharts = () => {
  // 重新初始化所有图表以反映新数据
  nextTick(() => {
    initOrderTrendChart()
    initOrderStatusChart()
    initMonthlySalesChart()
    initProductRankChart()
    initCustomerOrderChart()
  })
}

/**
 * 重置数据到初始状态
 */
const resetToInitialData = () => {
  // 重置概览数据
  overviewData.value = [
    {
      title: '总订单数',
      value: '2,456',
      trend: 15.2,
      icon: 'ShoppingCart',
      color: '#409EFF',
    },
    {
      title: '总销售额',
      value: '¥1.2M',
      trend: 8.7,
      icon: 'Money',
      color: '#67C23A',
    },
    {
      title: '平均订单额',
      value: '¥4,890',
      trend: -2.3,
      icon: 'TrendCharts',
      color: '#E6A23C',
    },
    {
      title: '活跃客户',
      value: '892',
      trend: 12.1,
      icon: 'User',
      color: '#F56C6C',
    },
  ]
  
  // 重置热销产品数据
  hotProducts.value = [
    { name: '高档真丝面料', sales: 156, revenue: 234000 },
    { name: '纯棉印花布', sales: 134, revenue: 189000 },
    { name: '羊毛呢料', sales: 128, revenue: 256000 },
    { name: '亚麻混纺布', sales: 98, revenue: 147000 },
    { name: '涤纶面料', sales: 87, revenue: 98000 },
  ]
  
  // 重置大客户订单数据
  bigOrders.value = [
    { customerName: '上海时装有限公司', orderCount: 45, totalAmount: 567000 },
    { customerName: '北京服饰集团', orderCount: 38, totalAmount: 489000 },
    { customerName: '广州纺织厂', orderCount: 32, totalAmount: 423000 },
    { customerName: '深圳制衣公司', orderCount: 28, totalAmount: 356000 },
    { customerName: '杭州丝绸企业', orderCount: 25, totalAmount: 298000 },
  ]
}

/**
 * 窗口大小变化时重新调整图表
 */
const handleResize = () => {
  orderTrendChartInstance?.resize()
  orderStatusChartInstance?.resize()
  monthlySalesChartInstance?.resize()
  productRankChartInstance?.resize()
  customerOrderChartInstance?.resize()
}

onMounted(async () => {
  await nextTick()

  // 初始化所有图表
  initOrderTrendChart()
  initOrderStatusChart()
  initMonthlySalesChart()
  initProductRankChart()
  initCustomerOrderChart()

  // 监听窗口大小变化
  window.addEventListener('resize', handleResize)
})
</script>

<style scoped>
.order-statistics {
  padding: 0;
}

.overview-section {
  margin-bottom: 20px;
}

.overview-card {
  height: 100px;
  cursor: pointer;
  transition: all 0.3s;
}

.overview-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.card-content {
  display: flex;
  align-items: center;
  height: 100%;
}

.card-icon {
  width: 50px;
  height: 50px;
  border-radius: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 12px;
  color: white;
}

.card-info {
  flex: 1;
}

.card-title {
  font-size: 12px;
  color: #909399;
  margin-bottom: 4px;
}

.card-value {
  font-size: 20px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 2px;
}

.card-trend {
  font-size: 11px;
  display: flex;
  align-items: center;
  gap: 2px;
}

.card-trend.positive {
  color: #67c23a;
}

.card-trend.negative {
  color: #f56c6c;
}

.filter-section {
  margin-bottom: 20px;
}

.filter-form {
  margin: 0;
}

.charts-section {
  margin-bottom: 20px;
}

.chart-card,
.table-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.chart-container {
  height: 300px;
  width: 100%;
}

.data-section {
  margin-top: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .overview-card {
    margin-bottom: 16px;
  }

  .card-content {
    flex-direction: column;
    text-align: center;
  }

  .card-icon {
    margin-right: 0;
    margin-bottom: 8px;
  }

  .chart-container {
    height: 250px;
  }

  .card-header {
    flex-direction: column;
    gap: 10px;
    align-items: flex-start;
  }

  .filter-form {
    display: block;
  }

  .filter-form .el-form-item {
    display: block;
    margin-bottom: 16px;
  }
}
</style>
